package com.hellobike.haxing.aop;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hellobike.haxing.common.ResponseCodeEnum;
import com.hellobike.haxing.order.result.Result;
import com.hellobike.haxing.order.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class ExceptionControllerAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<?> bindExceptionHandler(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        JSONArray jsonArray = new JSONArray();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(fieldError.getField(), fieldError.getDefaultMessage());
            jsonArray.add(jsonObject);
        });
        Result<Object> result = Result.error(jsonArray, ResponseCodeEnum.NO_PARAM.code(),ResponseCodeEnum.NO_PARAM.message());
        return result;
    }

    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public Result<?> runtimeException(Exception ex) {
        log.error("====RuntimeException==异常=",ex);
        return Result.error(ResponseCodeEnum.NO_PARAM.code(),ex.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Result<?> exception(Exception ex) {
        log.error("====exception==异常=",ex);
        return Result.error(ResponseCodeEnum.FAIL.code(),ResponseCodeEnum.FAIL.message());
    }
}
